﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Hr;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.MasterData;
using ESOL.WinUI.UICommon;

namespace ESOL.WinUI.Hr
{
    public partial class frmMaintainEmployeeLeaveApplication : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        private MstPersonEntity mSelectedPerson;
        private HrPersonLeaveApplicationEntity mSelectedPersonLeave;
        public ApproveType ThisApproveType { get; set; }
        #endregion

        #region Constructor
        public frmMaintainEmployeeLeaveApplication(HrPersonLeaveApplicationEntity entity)
        {
            InitializeComponent();
            mSelectedPersonLeave = entity;
        }

        public frmMaintainEmployeeLeaveApplication(MstPersonEntity person)
        {
            InitializeComponent();
            mSelectedPerson = person;
        }

        public frmMaintainEmployeeLeaveApplication()
        {
            InitializeComponent();
        }
        #endregion

        #region Functions
        private void SetPersonFields()
        {
            txtPerson.Text = "";
            txtPersonNameCn.Text = "";
            cmbStatus.SelectedIndex = -1;
            txtDepartment.Text = "";
            txtJoinDate.Text = "";
            txtContractEndDate.Text = "";
            if (mSelectedPerson == null)
            {
                return;
            }
            txtPerson.Text = mSelectedPerson.PersonCode;
            txtPersonNameCn.Text = mSelectedPerson.NameCn;
            cmbStatus.SetSelectedValue(mSelectedPerson.Status);
            MstDepartmentEntity department = MstDepartmentBs.GetMstDepartmentByID(mSelectedPerson.DepartmentId);
            if (department != null)
            {
                txtDepartment.Text = department.DepartmentName;
            }
            MstPositionEntity position = MstPositionBs.GetMstPositionByID(mSelectedPerson.PositionId);
            if (position != null)
            {
                txtPosition.Text = position.PositionName;
            }
            HrEmployeeEntity employee = HrEmployeeBs.GetHrEmployeeByPersonId(mSelectedPerson.PersonId);
            if (employee != null)
            {
                if (employee.JoinDate.ToString("yyyy-MM-dd") != "0001-01-01" && employee.JoinDate.ToString("yyyy-MM-dd") != "1900-01-01")
                {
                    txtJoinDate.Text = employee.JoinDate.ToString("yyyy-MM-dd");
                }
                if (employee.ContractEndDate.ToString("yyyy-MM-dd") != "0001-01-01" && employee.ContractEndDate.ToString("yyyy-MM-dd") != "1900-01-01")
                {
                    txtContractEndDate.Text = employee.ContractEndDate.ToString("yyyy-MM-dd");
                }
            }
        }

        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "PLAS", false);
        }
        private void SetFields()
        {
            if (mSelectedPersonLeave == null)
            {
                return;
            }
            if (string.IsNullOrEmpty(mSelectedPersonLeave.PersonId) == false)
            {
                mSelectedPerson = MstPersonBs.GetMstPersonByID(mSelectedPersonLeave.PersonId);
                SetPersonFields();
            }
            if (mSelectedPersonLeave.LeaveDate.ToString("yyyy-MM-dd") != "1900-01-01" &&
                 mSelectedPersonLeave.LeaveDate.ToString("yyyy-MM-dd") != "0001-01-01")
            {
                dtpLeaveDate.EditValue = mSelectedPersonLeave.LeaveDate;
            }
            cmbStatus.SetSelectedValue(mSelectedPersonLeave.Status);
            txtLeaveReason.Text = mSelectedPersonLeave.LeaveReason;
            txtUpload.Text = mSelectedPerson.Attachment;
            txtDmRemark.Text = mSelectedPersonLeave.DmRemark;
            UICommonFunctions.SetTextBoxDate(txtDmApprovedDate, mSelectedPersonLeave.DmApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtDmPerson, mSelectedPersonLeave.DmPerson);
            txtHrRemark.Text = mSelectedPersonLeave.HrRemark;
            UICommonFunctions.SetTextBoxDate(txtHrApprovedDate, mSelectedPersonLeave.HrApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtHrPerson, mSelectedPersonLeave.HrPerson);
            txtFinRemark.Text = mSelectedPersonLeave.FinRemark;
            UICommonFunctions.SetTextBoxDate(txtFinApprovedDate, mSelectedPersonLeave.FinApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtFinPerson, mSelectedPersonLeave.FinPerson);
            txtCeoRemark.Text = mSelectedPersonLeave.CeoRemark;
            UICommonFunctions.SetTextBoxDate(txtCeoApprovedDate, mSelectedPersonLeave.CeoApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCeoPerson, mSelectedPersonLeave.CeoPerson);

            UICommonFunctions.SetTextBoxDate(txtCreatedDate, mSelectedPersonLeave.CreatedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, mSelectedPersonLeave.CreatedBy);
            UICommonFunctions.SetTextBoxDate(txtLastModifiedDate, mSelectedPersonLeave.LastModifiedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtLastModifiedBy, mSelectedPersonLeave.LastModifiedBy);
        }

        private void SetEntity()
        {
            if (mSelectedPersonLeave == null)
            {
                mSelectedPersonLeave = new HrPersonLeaveApplicationEntity();
                mSelectedPersonLeave.ApplicationId = Guid.NewGuid().ToString();
            }
            if (mSelectedPerson != null)
            {
                mSelectedPersonLeave.PersonId = mSelectedPerson.PersonId;
                mSelectedPersonLeave.DepartmentId = mSelectedPerson.DepartmentId;
                mSelectedPersonLeave.PositioinId = mSelectedPerson.PositionId;
            }
            if (dtpLeaveDate.EditValue!=null)
            {
                mSelectedPersonLeave.LeaveDate = Convert.ToDateTime(dtpLeaveDate.EditValue);
            }
            else
            {
                mSelectedPersonLeave.LeaveDate = Convert.ToDateTime("1900-01-01");
            }
            mSelectedPersonLeave.Status = "PLAS01";
            mSelectedPersonLeave.LeaveReason = txtLeaveReason.Text;

            if (ThisActionType == ActionType.New)
            {
                mSelectedPersonLeave.CreatedDate = DateTime.Now;
                mSelectedPersonLeave.CreatedBy = CommonParameter.CurrentUser.PersonId;
            }
            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                mSelectedPersonLeave.LastModifiedDate = DateTime.Now;
                mSelectedPersonLeave.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
        }

        private bool CheckData()
        {
            if (mSelectedPerson == null)
            {
                MessageBox.Show("请选择一个员工！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtLeaveReason.Text))
            {
                MessageBox.Show("离职原因不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpLeaveDate.EditValue == null)
            {
                MessageBox.Show("离职日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return true;
        }

        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    bool isSuccessful = HrPersonLeaveApplicationBs.InsertHrPersonLeaveApplication(mSelectedPersonLeave);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    bool isSuccessful = HrPersonLeaveApplicationBs.UpdateHrPersonLeaveApplication(mSelectedPersonLeave);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    switch (ThisApproveType)
                    {
                        case ApproveType.DM:
                            mSelectedPersonLeave.DmApprovedDate = DateTime.Now;
                            mSelectedPersonLeave.DmPerson = CommonParameter.CurrentUser.PersonId;
                            mSelectedPersonLeave.DmRemark = txtDmRemark.Text;
                            break;
                        case ApproveType.HR:
                            mSelectedPersonLeave.HrApprovedDate = DateTime.Now;
                            mSelectedPersonLeave.HrPerson = CommonParameter.CurrentUser.PersonId;
                            mSelectedPersonLeave.HrRemark = txtHrRemark.Text;
                            break;
                        case ApproveType.FIN:
                            mSelectedPersonLeave.FinApprovedDate = DateTime.Now;
                            mSelectedPersonLeave.FinPerson = CommonParameter.CurrentUser.PersonId;
                            mSelectedPersonLeave.FinRemark = txtFinRemark.Text;
                            break;
                        case ApproveType.CEO:
                            mSelectedPersonLeave.CeoApprovedDate = DateTime.Now;
                            mSelectedPersonLeave.CeoPerson = CommonParameter.CurrentUser.PersonId;
                            mSelectedPersonLeave.CeoRemark = txtCeoRemark.Text;
                            break;
                        default:
                            return false;
                    }
                    bool isSuccessful = HrPersonLeaveApplicationBs.ApproveHrPersonLeaveApplication(mSelectedPersonLeave);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private void ResetControlsEnable()
        {
            txtDmRemark.Properties.ReadOnly = true;
            txtHrRemark.Properties.ReadOnly = true;
            txtFinRemark.Properties.ReadOnly = true;
            txtCeoRemark.Properties.ReadOnly = true;
            if (ThisActionType == ActionType.Approve)
            {
                switch (ThisApproveType)
                {
                    case ApproveType.DM:
                        txtDmRemark.Properties.ReadOnly = false;
                        break;
                    case ApproveType.HR:
                        txtHrRemark.Properties.ReadOnly = false;
                        break;
                    case ApproveType.FIN:
                        txtFinRemark.Properties.ReadOnly = false;
                        break;
                    case ApproveType.CEO:
                        txtCeoRemark.Properties.ReadOnly = false;
                        break;
                }
            }
        }
        #endregion

        #region Event
        private void frmMaintainPersonLeaveApplication_Load(object sender, EventArgs e)
        {
            BindComboBox();
            SetPersonFields();
            SetFields();
            ResetControlsEnable();
        }

        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_Approve()
        {
            if (mSelectedPersonLeave == null)
            {
                return;
            }
            switch (ThisApproveType)
            {
                case ApproveType.DM:
                    mSelectedPersonLeave.Status = "PLAS02";
                    break;
                case ApproveType.HR:
                    mSelectedPersonLeave.Status = "PLAS04";
                    break;
                case ApproveType.FIN:
                    mSelectedPersonLeave.Status = "PLAS06";
                    break;
                case ApproveType.CEO:
                    mSelectedPersonLeave.Status = "PLAS08";
                    break;
                default:
                    return;
            }
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_Reject()
        {
            if (mSelectedPersonLeave == null)
            {
                return;
            }
            switch (ThisApproveType)
            {
                case ApproveType.DM:
                    mSelectedPersonLeave.Status = "PLAS03";
                    break;
                case ApproveType.HR:
                    mSelectedPersonLeave.Status = "PLAS05";
                    break;
                case ApproveType.FIN:
                    mSelectedPersonLeave.Status = "PLAS07";
                    break;
                case ApproveType.CEO:
                    mSelectedPersonLeave.Status = "PLAS09";
                    break;
                default:
                    return;
            }
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private void txtPerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery(true);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                mSelectedPerson = frm.SelectedPerson;
                SetPersonFields();
            }
            else
            {
                mSelectedPerson = null;
                SetPersonFields();
            }
        }
        private bool Upload(string filename)
        {
            try
            {
                if (string.IsNullOrEmpty(filename) == false)
              {
              using (EsolWevServices.EsolService service = new EsolWevServices.EsolService())
                    {
                        //SelectedPerson.AccessoryPathway = SelectedPerson.PersonCode + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "." + CommonFunctions.GetFileExtension(FileName);
                        string path = service.GetPersonLeave();
                        byte[] bytes = CommonFunctions.FileToByte(filename);
                        string errMsg = "";

                        bool result = service.UploadFileNew(bytes, path + "\\" + CommonFunctions.GetFilePrefix(filename), out errMsg);
                        if (string.IsNullOrEmpty(errMsg) == false)
                        {
                            MessageBox.Show(errMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }

                        result = MstPersonBs.UpdateMstPerson(mSelectedPerson);

                        return result;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        private bool Download(string FilefullName)
        {
            try
            {
                if (string.IsNullOrEmpty(FilefullName) == false)
                {
                    using (EsolWevServices.EsolService service = new EsolWevServices.EsolService())
                    {
                        string errMsg = "";
                        string path = service.GetPersonLeave();
                        byte[] bytes = service.DownloadFileNew(path + "\\" + CommonFunctions.GetFilePrefix(FilefullName), out errMsg);

                        if (string.IsNullOrEmpty(errMsg) == false)
                        {
                            MessageBox.Show(errMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                        Image image = CommonFunctions.byteArrayToImage(bytes);
                        image.Save(FilefullName);
                        image.Dispose();
                        return true;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        #endregion

        private void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                if (ThisActionType != ActionType.Modify)
                {
                    MessageBox.Show("用户必须先保存才能上传附件!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                OpenFileDialog fd = new OpenFileDialog();
                fd.Filter = "JPG文件|*.jpg|PNG文件|*.png";
                fd.Multiselect = false;
                if (fd.ShowDialog() == DialogResult.OK)
                {

                    Cursor = Cursors.WaitCursor;
                    bool result = Upload (fd.FileName);
                    Cursor = Cursors.Default;
                    if (result)
                    {
                        txtUpload.Text = CommonFunctions.GetFilePrefix(fd.FileName);
                        MessageBox.Show("上传成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
         txtDownload.Text = txtUpload.Text;
            if (ThisActionType == ActionType.New)
            {
                MessageBox.Show("没有可下载的附件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            SaveFileDialog fd = new SaveFileDialog();
            fd.FileName = txtDownload.Text;
            if (fd.ShowDialog() == DialogResult.OK)
            {
                Cursor = Cursors.WaitCursor;
                bool result = Download(fd .FileName);
                Cursor = Cursors.Default;
                if (result)
                { MessageBox.Show("下载成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); }

            }
        }
        }
    }

